package com.example.selfcontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.selfcontrol.config.Response;
import com.example.selfcontrol.dto.MessageDTO;
import com.example.selfcontrol.dto.MessageTotalDTO;
import com.example.selfcontrol.entity.Message;
import com.example.selfcontrol.mapper.MessageMapper;
import com.example.selfcontrol.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper ;

    @Override
    public Response addMessage(MessageDTO messageDTO) {
        Long userId = messageDTO.getUserId() ;
        Long notifyId = messageDTO.getNotifyId() ;
        String content = messageDTO.getContent() ;

        Message message = new Message(userId,notifyId,content) ;
        System.out.println(message);


        try {
            messageMapper.insert(message) ;
        }catch (Exception e) {
            e.printStackTrace();
            return Response.fail() ;
        }
        return Response.ok() ;
    }


    @Override
    public List<Message> getMessage(Long userId, Long notifyId) {
        QueryWrapper<Message> wrapper = new QueryWrapper<>() ;
        wrapper.like("notify_id",notifyId).like("user_id",userId) ;
        return messageMapper.selectList(wrapper) ;

    }

    @Override
    public int getUnReadMessage(Long userId, Long notifyId) {
        QueryWrapper<Message> wrapper = new QueryWrapper<>() ;
        wrapper.like("notify_id",notifyId).like("user_id",userId).like("is_read",0) ;
        return messageMapper.selectCount(wrapper) ;
    }

    @Override
    public Response ChangeReadStatus(Long userId, Long notifyId, List<String> readedList) {

        for(String x : readedList) {
            int id = Integer.valueOf(x).intValue() ;
            Message message = messageMapper.selectById(id) ;
            message.setIsRead(1);
            messageMapper.updateById(message) ;
        }

        return Response.ok() ;
    }

    @Override
    public Response DeleteMessage(Long userId, Long notifyId, List<String> readedList) {

        for(String x : readedList) {
            int id = Integer.valueOf(x).intValue() ;
            messageMapper.deleteById(id) ;
        }

        return Response.ok() ;
    }

}
